﻿using System;
using System.Web.Mvc;

namespace Web.Infrastructure.Mvc.FileUpload
{
    public class FileController : Controller
    {
        [HttpPost]
        [Authorize]
        public ActionResult Upload(string path)
        {
            if (Request.Files.Count > 0 && Request.Files[0] != null && !string.IsNullOrEmpty(Request.Files[0].FileName))
            {
                try
                {
                    var file = Request.Files[0];
                    string md5Name = Web.Infrastructure.Mvc.FileUpload.UploadHelper.Save(file, path);

                    var fileName = string.IsNullOrEmpty(path) ? md5Name : path + "/" + md5Name;
                    return Content(Web.Infrastructure.Mvc.FileUpload.UploadHelper.ToJson(new { error = 0, url = fileName }));
                }
                catch (Exception ex)
                {
                    return Content(Web.Infrastructure.Mvc.FileUpload.UploadHelper.ToJson(new { error = 1, msg = ex.Message }));
                }
            }
            return Content(Web.Infrastructure.Mvc.FileUpload.UploadHelper.ToJson(new { error = 1, msg = "未选择文件" }));
        }
    }
}